package com.scaffold.service.impl;


import com.scaffold.service.HelloApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloService implements HelloApiService {

    @Autowired
    RestTemplate restTemplate;

    public String sayHi() {
        return restTemplate.getForObject("http://service-demo-func/sayHi", String.class);
    }

    public String sayHiMessage(String message) {
        try {
            // 构建完整的URL
            String url = "http://service-demo-func/sayHiMessage";

            // 发起POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, message, String.class);

            // 检查HTTP状态码是否为成功
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                // 如果不是成功的状态码，则抛出异常
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatusCode());
            }
        } catch (Exception e) {
            // 记录异常信息
            System.err.println("Error occurred while calling remote service: " + e.getMessage());
            // 返回一个默认值或者抛出自定义异常
            return "Error: Unable to process request.";
        }
    }
}

